#include <iostream>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
#include "video_play_demo.h"

bool decode_video(const char *input_file) {
    AVFormatContext *format_ctx = nullptr;
    unsigned int video_stream_index = 0;
    AVCodecContext *codec_ctx = nullptr;
    const AVCodec *codec;
    AVPacket packet;
    AVFrame *frame = nullptr;
    int frame_number = 0;

    // 初始化 FFmpeg
    avformat_network_init();

    // 打开输入文件
    if (avformat_open_input(&format_ctx, input_file, nullptr, nullptr) != 0) {
        return false;
    }

    // 查找流信息
    if (avformat_find_stream_info(format_ctx, nullptr) < 0) {
        return false;
    }

    // 查找视频流
    for (unsigned i = 0; i < format_ctx->nb_streams; ++i) {
        if (format_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
            video_stream_index = i;
            break;
        }
    }

    if (video_stream_index == -1) {
        return false;
    }

    codec = avcodec_find_decoder(format_ctx->streams[video_stream_index]->codecpar->codec_id);
    if (!codec) {
        return false;
    }

    codec_ctx = avcodec_alloc_context3(codec);
    if (!codec_ctx) {
        return false;
    }

    if (avcodec_parameters_to_context(codec_ctx, format_ctx->streams[video_stream_index]->codecpar) < 0) {
        return false;
    }

    if (avcodec_open2(codec_ctx, codec, nullptr) < 0) {
        return false;
    }

    // 分配包和帧
    frame = av_frame_alloc();
    if (!frame) {
        return false;
    }

    // 读取帧
    while (av_read_frame(format_ctx, &packet) >= 0) {
        if (packet.stream_index == video_stream_index) {
            if (avcodec_send_packet(codec_ctx, &packet) < 0) {
                av_packet_unref(&packet);
                continue;
            }

            while (avcodec_receive_frame(codec_ctx, frame) == 0) {
                frame_number++;
                // 处理解码后的帧
            }
            av_packet_unref(&packet);
        }
    }
    // 释放资源
    av_frame_free(&frame);
    avcodec_free_context(&codec_ctx);
    avformat_close_input(&format_ctx);

    return true;
}

int main() {
    const char* input_file = "../resources/video/video.mp4";
    if (decode_video(input_file)){
        std::cout << "Decode video successfully." << std::endl;
    } else {
        std::cout << "Decode video failed." << std::endl;
    }
    /*const char* file_path = "../resources/video/video.mp4";
    play_MP4(file_path);*/
    return 0;
}

